import importlib
from .config import caches


class Cache:                   # 缓存的基类
    def __init__(self):
        self.cache = dict()

    def get(self, key):
        pass

    def set(self, key, value):
        pass

    def delete(self, key):
        pass

    def __setitem__(self, key, value):
        self.set(key, value)

    def __getitem__(self, key):
        return self.get(key)

    def __delitem__(self, key):
        self.delete(key)

    def __set__(self, instance, value):
        return self


_cache_list = {}
_cache_address = {}


for k, v in caches:
    assert isinstance(v['BACKEND'], str)
    pkg, cls = v['BACKEND'].rsplit(".", 1)
    model = importlib.import_module(pkg)
    cache_cls = getattr(model, cls)
    if not issubclass(cache_cls, Cache):
        raise TypeError
    _cache_list[k] = cache_cls

    assert isinstance(v['LOCATION'], str)
    ip, port = v['LOCATION'].rsplit(":", 1)
    _cache_address[k] = (ip, port)


    # caches = dict()
    # redis = caches["redis"]
    # info = Caches['redis']
    # backend = info['BACKEND']
    # cache_addr = info["LOCATION"]

    # assert isinstance(backend, str)
    # pkg, cls = backend.rsplit(".", 1)
    # model = importlib.import_module(pkg)
    # cache_cls = getattr(model, cls)
    #
    # if not issubclass(cache_cls, Cache):
    #     raise TypeError
    # _cache_list["default"] = cache_cls

    # assert isinstance(cache_addr, str)
    # ip, port = cache_addr.rsplit(":", 1)
    # cache_address["location"] = (ip, port)
    #
    #
    # memcached = caches["memcached"]
    #
    # info = Caches['memcached']
    # backend = info['BACKEND']
    # cache_addr = info["LOCATION"]
    #
    # assert isinstance(backend, str)
    # pkg, cls = backend.rsplit(".", 1)
    # model = importlib.import_module(pkg)
    # cache_cls = getattr(model, cls)
    #
    # if not issubclass(cache_cls, Cache):
    #     raise TypeError
    # cache_list["default"] = cache_cls
    #
    # assert isinstance(cache_addr, str)
    # ip, port = cache_addr.rsplit(":", 1)
    # cache_address["location"] = (ip, port)